package javamobile.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybeans.dao.DAOException;

import javamobile.model.*;

public class LoginAction extends Action{

	private DAOFactory factory;
	
	public LoginAction(Model model) {
		factory = model.getDAOFactory();
	}
	
	@Override
	public String getName() {return "login.do";}

	@Override
	public Map<String, Object> perform(Map<String, Object> input) {
		System.out.println("Performing login action!");
		Map<String, Object> output = new HashMap<String, Object>();
		List<String> errors = new ArrayList<String>();
		output.put("errors", errors);
		
		String username = (String) input.get("username");
		String password = (String) input.get("password");
		
		if (username.length() == 0) {
			errors.add("Username is required");
		}
		if (password.length() == 0) {
			errors.add("Password is required");
		}
		if (errors.size() != 0) {
        	return output;
        }
		
		// Look up the user
		User user;
		try {
        	user = factory.lookupUser(username);
        } catch (DAOException e) {
        	errors.add(e.getMessage());
        	return output;
        }
		if (user == null) {
            errors.add("User "+username+" not found");
            return output;
        }
        if (!password.equals(user.getPassword())) {
            errors.add("Incorrect password");
            return output;
        }
		return output;
	}

}
